package com.learn.springcloud.hystrixexplainindetailconsumer.request.collapser.collapse;

import com.learn.springcloud.hystrixexplainindetailconsumer.bean.User;
import com.learn.springcloud.hystrixexplainindetailconsumer.request.collapser.command.UserBatchCommand;
import com.learn.springcloud.hystrixexplainindetailconsumer.request.collapser.service.RequestCollapserExtendService;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 请求合并
 * @Time : 2018/8/6 20:01
 * @Version : 1.0
 */
public class UserCollapseCommand extends HystrixCollapser<List<User>, User, Long> {

    private RequestCollapserExtendService requestCollapserService;

    private Long userId;

    public UserCollapseCommand(HystrixCollapserKey collapserKey, RequestCollapserExtendService requestCollapserService, Long userId) {
        super(
                Setter.withCollapserKey(
                        HystrixCollapserKey.Factory.asKey("eee")
                )
                .andCollapserPropertiesDefaults(
                        HystrixCollapserProperties.Setter().withTimerDelayInMilliseconds(100)
                )
        );
        this.requestCollapserService = requestCollapserService;
        this.userId = userId;
    }

    @Override
    public Long getRequestArgument() {
        return userId;
    }

    @Override
    protected HystrixCommand<List<User>> createCommand(Collection<CollapsedRequest<User, Long>> collapsedRequests) {
        List<Long> userIds = new ArrayList<>(collapsedRequests.size());
        userIds.addAll(collapsedRequests.stream().map(CollapsedRequest::getArgument).collect(Collectors.toList()));
        return new UserBatchCommand(requestCollapserService,userIds);
    }

    @Override
    protected void mapResponseToRequests(List<User> batchResponse, Collection<CollapsedRequest<User, Long>> collapsedRequests) {
        int count = 0;
        for(CollapsedRequest<User, Long> collapsedRequest : collapsedRequests){
            User user = batchResponse.get(count++);
            collapsedRequest.setResponse(user);
        }
    }
}
